<template>
  <view class="container" :style="appThemeStyle">
    <z-paging ref="paging"
              v-model="list"
              class="notice-list"
              @query="getlist">
      <!-- tab栏 -->
      <template #top>
        <u-tabs
            :list="tabs"
            :is-scroll="false"
            v-model="curTab"
            :active-color="appTheme.mainBg"
            :duration="0.2"
            @change="onChangeTab"

        />
      </template>
      <!-- 订单列表 -->
      <view class="order-list">
        <view style="box-shadow: 0px 0px 28rpx 1rpx rgba(78, 101, 153, 0.14);"
              class="order-item"
              v-for="(item, index) in list"
              :key="index"
        >
          <view class="item-top">
            <view class="item-top-left">
              <text class="order-time">{{ item.createTime }}</text>
            </view>
            <view class="item-top-right">
              <text class="state-text">{{ item.state_text }}</text>
            </view>
          </view>
          <!-- 商品列表 -->
          <view class="goods-list">
            <view
                class="goods-item"
                v-for="(goods, idx) in item.orderDetails"
                :key="idx"
                @click="handleCheckItem(item.pid)"
            >
              <div style="width: 40rpx; height: 40rpx">
                <img
                    v-if="inArray(item.pid, checkedIds)"
                    src="/static/svg/check.svg"
                    alt="" style="width: 40rpx; height: 40rpx"
                />
                <img v-else src="/static/svg/uncheck.svg" alt="" style="width: 40rpx; height: 40rpx"/>
              </div>
              <!-- 商品图片 -->
              <view class="goods-image">
                <image
                    class="image"
                    :src="goods.url"
                    mode="scaleToFill"
                ></image>
              </view>
              <!-- 商品信息 -->
              <view class="goods-content">
                <view class="goods-title">
                  <text class="twoline-hide">{{ goods.title }}</text>
                </view>
                <view class="goods-props clearfix">
                  <!-- <view class="goods-props-item" v-for="(props, idx) in goods.goods_props" :key="idx">
                    <text>{{ props.value.name }}</text>
                  </view> -->
                  <div class="goods-props-item"> 分类：{{ goods.name }}</div>
                </view>
              </view>
              <!-- 交易信息 -->
              <view class="goods-trade">
                <view class="goods-price">
                  <text class="unit">￥</text>
                  <text class="value">{{ goods.price }}</text>
                </view>
                <view class="goods-num">
                  <text>×{{ goods.num }}</text>
                </view>
              </view>
            </view>
          </view>
          <!-- 订单合计 -->
          <div class="f ac xe">
            <view class="order-total " style="height: 20rpx">
              <text>共{{ item.totalNum }}件商品，总金额</text>
              <text class="unit">￥</text>
              <text class="money">{{ item.payPrice }}</text>

            </view>
            <!--            <div style="width: 100rpx;margin-left: 20rpx">-->
            <!--              <u-button text="保單" type="primary" size="mini"></u-button>-->
            <!--            </div>-->
          </div>
          <!-- 订单操作 -->
          <view
              class="order-handle"
          >
            <view class="btn-group clearfix">
              <!-- 未支付取消订单 -->
              <block>
                <view class="btn-item" @click="onCancel(item.order_id)">
                  报单
                </view>
              </block>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
    <view class="footer-fixed" style="border-top:1px solid #7F7F7F">
      <view class="all-radio f ac" @click="handleCheckAll()">
        <img
            v-if="checkedIds.length > 0 && checkedIds.length === list.length"
            src="/static/svg/check.svg"
            alt=""
            style="width: 40rpx; height: 40rpx"
        />
        <img
            v-else
            src="/static/svg/uncheck.svg"
            alt=""
            style="width: 40rpx; height: 40rpx"
        />
        <div class="ml5r">全选</div>
      </view>
      <view class="total-info">
        <text>合计：</text>
        <view class="goods-price">
          <text class="unit">￥</text>
          <text class="value">{{ totalPrice || 0 }}</text>
        </view>
      </view>
      <view class="cart-action">
        <view class="btn-wrapper">
          <!-- dev:下面的disabled条件使用checkedIds.join方式判断 -->
          <!-- dev:通常情况下vue项目使用checkedIds.length更合理, 但是length属性在微信小程序中不起作用 -->
          <view
              class="btn-item btn-main"
              :class="{ disabled: checkedIds.join() == '' }"
              @click="handleOrder()"
          >
            <text>
              一键报单 {{ checkedIds.length > 0 ? `(${checkedIds.length})` : "" }}
            </text>
          </view>

        </view>
      </view>
    </view>


  </view>
</template>

<script>
import {
  DeliveryStatusEnum,
  DeliveryTypeEnum,
  OrderStatusEnum,
  PayStatusEnum,
  ReceiptStatusEnum,
} from "@/common/enum/order";
import {getEmptyPaginateObj, getMoreListData} from "@/core/app";
import * as OrderApi from "@/api/order";
import {getOrderList, updateShopping} from "../../api/shoppingCart";
import ZPaging from "../../uni_modules/z-paging/components/z-paging/z-paging.vue";
import {inArray} from "../../utils/util";


// 每页记录数量
const pageSize = 15;

// tab栏数据
const tabs = [
  {
    name: `已上报`,
    value: 0,
  },
  {
    name: `未上报`,
    value: 1,
  },
];

export default {
  components: {ZPaging},
  data() {
    return {
      // 枚举类
      DeliveryStatusEnum,
      DeliveryTypeEnum,
      OrderStatusEnum,
      PayStatusEnum,
      ReceiptStatusEnum,

      // 当前页面参数
      options: {dataType: "all"},
      // tab栏数据
      tabs,
      // 当前标签索引
      curTab: 0,
      // 订单列表数据
      // list: getEmptyPaginateObj(),
      list: [],
      checkedIds: []
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 初始化当前选中的标签
    this.initCurTab(options);

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面的卸载
   */
  onUnload() {
    // 卸载全局事件订阅
    uni.$off("syncRefresh");
  },

  methods: {
    inArray,
    async getlist(pageNo, pageNum = 10) {
      //''全部 0  创建订单/待发货 2 已发货/待收货  3已完成
      let mapArr = ['', 1, 2, 3]
      let data = {
        pageSize: pageNo,
        pageNum: pageNum,
        orderStatus: mapArr[this.curTab],
      }
      const res = await getOrderList(data);
      if (res.rows.length == 0) {
        this.$refs.paging.complete()
        return
      }
      this.$refs.paging.complete(res.rows);
    },
    // 初始化当前选中的标签
    initCurTab(options) {
      const app = this;
      if (options.dataType) {
        const index = app.tabs.findIndex(
            (item) => item.value == options.dataType
        );
        app.curTab = index > -1 ? index : 0;
      }
    },
    // 选中商品
    async handleCheckItem(cartId) {
      // const res = await updateShopping({id: cartId});
      // if (res.code != 200) {
      //   this.$toast(res.msg);
      //   return;
      // }
      const {checkedIds} = this;
      const index = checkedIds.findIndex((id) => id === cartId);
      index < 0 ? checkedIds.push(cartId) : checkedIds.splice(index, 1);
      // this.getCartList();
    },
// 结算选中的商品
    handleOrder() {
      uni.setStorageSync("orderInfo", arr);
      let arr = this.list.filter((item) => item.isSelect == true);
      uni.setStorageSync("orderInfo", arr);

      if (this.checkedIds.length) {
        const cartIds = this.checkedIds.join();
        this.$navTo("pages/checkout/index", {mode: "cart", cartIds});
      }
    },
    // 全选事件
    handleCheckAll() {
      const {checkedIds, list} = this;
      this.checkedIds =
          checkedIds.length === list.length
              ? []
              : list.map((item) => item.pid);
    },
    // 初始化订单列表数据
    initList(newList) {
      newList.data.forEach((item) => {
        item.total_num = 0;
        item.goods.forEach((goods) => {
          item.total_num += goods.total_num;
        });
      });
      return newList;
    },

    // 获取当前标签项的值
    getTabValue() {
      return this.tabs[this.curTab].value;
    },

    // 切换标签项
    onChangeTab(index) {
      const app = this;
      // 设置当前选中的标签
      app.curTab = index.value;
      // 刷新订单列表
      // app.onRefreshList();
      this.$refs.paging.reload()
    },

    // 刷新订单列表
    onRefreshList() {
      this.list = getEmptyPaginateObj();
      setTimeout(() => {
        this.mescroll.resetUpScroll();
      }, 120);

    },

    // 取消订单
    onCancel(orderId) {
      const app = this;
      uni.showModal({
        title: "友情提示",
        content: "确认要报单吗？",
        success(o) {
          if (o.confirm) {
            OrderApi.cancel(orderId).then((result) => {
              // 显示成功信息
              app.$toast(result.message);
              // 刷新订单列表
              app.onRefreshList();
            });
          }
        },
      });
    },

    // 确认收货
    onReceipt(orderId) {
      const app = this;
      uni.showModal({
        title: "友情提示",
        content: "确认收到商品了吗？",
        success(o) {
          if (o.confirm) {
            OrderApi.receipt(orderId).then((result) => {
              // 显示成功信息
              app.$success(result.message);
              // 刷新订单列表
              app.onRefreshList();
            });
          }
        },
      });
    },

    // 点击去支付
    onPay(orderId) {
      this.$navTo("pages/checkout/cashier/index", {orderId});
    },
    // 跳转到订单评价页
    handleTargetComment(orderId) {
      this.$navTo("pages/order/comment/index", {orderId});
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .u-tabs__wrapper__nav__item {
  flex: 1;
}

// 底部操作栏
.footer-fixed {
  display: flex;
  align-items: center;
  height: 96rpx;
  background: #fff;
  padding: 0 30rpx;
  position: fixed;
  bottom: var(--window-bottom);
  left: 0;
  right: 0;
  z-index: 11;

  .all-radio {
    width: 140rpx;
    display: flex;
    align-items: center;

    .radio {
      margin-bottom: -4rpx;
      transform: scale(0.76);
    }
  }

  .total-info {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 30rpx;

    .goods-price {
      vertical-align: bottom;
      color: $main-bg;

      .unit {
        font-size: 24rpx;
      }

      .value {
        font-size: 32rpx;
      }
    }
  }

  .cart-action {
    width: 200rpx;

    .btn-wrapper {
      height: 100%;
      display: flex;
      align-items: center;
    }

    .btn-item {
      flex: 1;
      font-size: 28rpx;
      height: 72rpx;
      color: #fff;
      border-radius: 50rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    // 去结算按钮
    .btn-main {
      background: linear-gradient(to right, $main-bg, $main-bg2);
      color: $main-text;

      // 禁用按钮
      &.disabled {
        opacity: 0.6;
      }
    }
  }
}

// 项目内容
.order-item {
  margin: 20rpx auto 20rpx auto;
  padding: 30rpx 30rpx;
  width: 94%;
  box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
  border-radius: 16rpx;
  background: #fff;
}

// 项目顶部
.item-top {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  margin-bottom: 40rpx;

  .order-time {
    color: #777;
  }

  .state-text {
    color: $main-bg;
  }
}

// 商品列表
.goods-list {
  // 商品项
  .goods-item {
    display: flex;
    margin-bottom: 40rpx;

    // 商品图片
    .goods-image {
      width: 180rpx;
      height: 180rpx;

      .image {
        display: block;
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
    }

    // 商品内容
    .goods-content {
      flex: 1;
      padding-left: 16rpx;
      padding-top: 16rpx;

      .goods-title {
        font-size: 26rpx;
        max-height: 76rpx;
      }

      .goods-props {
        margin-top: 14rpx;
        color: #ababab;
        font-size: 24rpx;
        overflow: hidden;

        .goods-props-item {
          padding: 4rpx 16rpx;
          border-radius: 12rpx;
          background-color: #fcfcfc;
        }
      }
    }

    // 交易信息
    .goods-trade {
      padding-top: 16rpx;
      width: 150rpx;
      text-align: right;
      color: $uni-text-color-grey;
      font-size: 26rpx;

      .goods-price {
        vertical-align: bottom;
        margin-bottom: 16rpx;

        .unit {
          margin-right: -2rpx;
          font-size: 24rpx;
        }
      }
    }
  }
}

// 订单合计
.order-total {
  font-size: 26rpx;
  vertical-align: bottom;
  text-align: right;
  height: 40rpx;
  margin-bottom: 30rpx;

  .unit {
    margin-left: 8rpx;
    margin-right: -2rpx;
    font-size: 26rpx;
  }

  .money {
    font-size: 28rpx;
  }
}

// 订单操作
.order-handle {
  .btn-group {
    .btn-item {
      border-radius: 10rpx;
      padding: 8rpx 20rpx;
      margin-left: 15rpx;
      font-size: 26rpx;
      float: right;
      color: #383838;
      border: 1rpx solid #a8a8a8;

      &:last-child {
        margin-left: 0;
      }

      &.active {
        color: $main-bg;
        border: 1rpx solid $main-bg;
      }
    }
  }
}
</style>
